//
//  ExpresserTextField.m
//  TengyunStation
//
//  Created by Johnny on 15/8/24.
//  Copyright (c) 2015年 xingrong. All rights reserved.
//

#import "ExpresserTextField.h"
#import "ExpresserCell.h"
#import "DSToast.h"
#import "TSHeader.h"
#import "Singleton.h"

#define CellHeight      55.0

@implementation ExpresserTextField

- (void)awakeFromNib {
    if (!_expresserTabelView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(self.frame.origin.x, self.frame.origin.y + self.frame.size.height - 0.5, self.frame.size.width, 55)];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.layer.borderColor = LineColor.CGColor;
        tableView.layer.borderWidth = 0.5;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _expresserTabelView = tableView;
    }
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldShouldBeginEditing) name:UITextFieldTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidEndEditing) name:UITextFieldTextDidEndEditingNotification object:nil];
    _isShowTableView = NO;
    _isExecuteDelegate = NO;
    [self addTarget:self action:@selector(textFieldEditingChanged:) forControlEvents:UIControlEventEditingChanged];
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self awakeFromNib];
    }
    return self;
}

- (void)reloadTableView {
    if (!_isShowTableView) {
        [self showTableView];
    }
    float height = _expresserList.count * CellHeight;
    if (height > _maxTableHeight) {
        height = _maxTableHeight;
    }
    _expresserTabelView.frame = CGRectMake(_expresserTabelView.frame.origin.x, _expresserTabelView.frame.origin.y, _expresserTabelView.frame.size.width, height);
    [_expresserTabelView reloadData];
}

- (void)showTableView {
    [self.superview addSubview:_expresserTabelView];
    _isShowTableView = YES;
}

- (void)removeTableView {
    [_expresserTabelView removeFromSuperview];
    _isShowTableView = NO;
}

#pragma mark Notification
- (void)showKeyboard:(NSNotification *)notification {
    CGSize size = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    _maxTableHeight = [UIScreen mainScreen].bounds.size.height - self.frame.size.height - self.frame.origin.y - size.height - 64 - 5;
    [self textFieldShouldBeginEditing];
}

#pragma mark UITextFieldDelegate
- (void)textFieldShouldBeginEditing {
    NSString *sqlString = [NSString stringWithFormat:@"WHERE websiteId = '%@' AND telephone like '%%%@%%' ORDER BY saveday DESC",[Singleton shareInstance].userMessage.websiteId,self.text];
    _expresserList = [ExpresserDBModel findByCriteria:sqlString];
    [self reloadTableView];
}

- (void)textFieldDidEndEditing {
    if (_isShowTableView) {
        [self removeTableView];
    }
    if (self.text.length == 11 && _isExecuteDelegate) {
        _isExecuteDelegate = NO;
        if ([_expresserDelegate respondsToSelector:@selector(didFinishEditingExpresserTextField)]) {
            [_expresserDelegate didFinishEditingExpresserTextField];
        }
    }
}

#pragma mark UITextFieldAction
- (void)textFieldEditingChanged:(UITextField *)textField {
    if (textField.text.length < 11) {
        NSString *sqlString = [NSString stringWithFormat:@"WHERE websiteId = '%@' AND telephone like '%%%@%%' ORDER BY saveday DESC",[Singleton shareInstance].userMessage.websiteId,self.text];
        _expresserList = [ExpresserDBModel findByCriteria:sqlString];
        [self reloadTableView];
    } else {
        textField.text = [textField.text substringToIndex:11];
        _isExecuteDelegate = YES;
        [self resignFirstResponder];
    }
}

#pragma mark UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _expresserList.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CellHeight;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIndentifier = @"ExpresserCell";
    ExpresserCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"ExpresserCell" owner:self options:nil] lastObject];
    }
    cell.delegate = self;
    ExpresserDBModel *expresser = [_expresserList objectAtIndex:indexPath.row];
    [cell reloadExpresserCellWithExpresserModel:expresser Text:self.text];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ExpresserDBModel *expresser = [_expresserList objectAtIndex:indexPath.row];
    self.text = expresser.telephone;
    _isExecuteDelegate = YES;
    [self resignFirstResponder];
}

#pragma mark ExpresserCellDelegate
- (void)removeExpresserCell:(ExpresserCell *)cell {
    NSIndexPath *indexPath = [_expresserTabelView indexPathForCell:cell];
    ExpresserDBModel *expresser = [_expresserList objectAtIndex:indexPath.row];
    [expresser deleteObject];
    NSMutableArray *mutableArray = [NSMutableArray arrayWithArray:_expresserList];
    [mutableArray removeObject:expresser];
    _expresserList = mutableArray;
    [self reloadTableView];
}

- (void)dealloc {
    _expresserList = nil;
    _expresserTabelView = nil;
    _expresserDelegate = nil;
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidBeginEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidEndEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

@end
